<template>
  <div class="image-manager">
    <input 
      type="file" 
      ref="fileInput"
      accept="image/*"
      :multiple="multiple"
      @change="handleFileSelect"
      class="file-input"
    >

    <button @click="triggerFileInput" class="upload-button">
      上传图片
    </button>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'

const props = defineProps({
  type: {
    type: String,
    required: true,
    validator: (value) => ['category', 'person', 'face', 'object'].includes(value)
  },
  multiple: {
    type: Boolean,
    default: false
  }
})
const emit = defineEmits(['upload-success', 'upload-error'])
const fileInput = ref(null)

const triggerFileInput = () => {
  fileInput.value?.click()
}

const handleFileSelect = async (event) => {
  const input = event.target
  if (!input.files?.length) return

  // 如果不是多文件上传，但选择了多个文件，只取第一个
  if (!props.multiple && input.files.length > 1) {
    emit('upload-error', '只能选择一个文件')
    return
  }

  // 验证文件类型和大小
  for (const file of input.files) {
    if (!file.type.match(/^image\/(jpeg|png|gif)$/)) {
      emit('upload-error', `文件 ${file.name} 不是支持的格式（仅支持 JPG、PNG 和 GIF）`)
      return
    }
    if (file.size > 10 * 1024 * 1024) {
      emit('upload-error', `文件 ${file.name} 超过大小限制（最大10MB）`)
      return
    }
  }

  const formData = new FormData()
  if (props.multiple) {
    Array.from(input.files).forEach(file => {
      formData.append('file', file)
    })
  } else {
    formData.append('file', input.files[0])
  }
  formData.append('type', props.type)

  try {
    let url = 'http://111.229.88.2:8000'
    switch (props.type) {
      case 'object':
        url += '/detect_objects'
        break
      case 'face':
        url += '/recognize_face'
        break
      case 'person':
        url += '/detect_persons'
        break
      default:
        url += '/api/upload'
    }

    const response = await axios.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    emit('upload-success', response.data)
  } catch (error) {
    console.error('Upload error:', error.response || error)
    emit('upload-error', error.response?.data?.detail || error.message || '上传失败')
  }

  // 清除文件选择，允许重复选择相同文件
  input.value = ''
}
</script>

<style scoped>
.image-manager {
  margin-bottom: 1rem;
}

.file-input {
  display: none;
}

.upload-button {
  padding: 0.75rem 1.5rem;
  background-color: #4a90e2;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.2s;
}

.upload-button:hover {
  background-color: #357abd;
}
</style> 